package gui;

import database.entity.Contact;
import database.entity.User;
import database.entity.ContactGroup;
import database.entity.Mail;
import database.entity.MailBox;
import gui.component.ContactGroupRenderer;
import gui.component.ContactRenderer;
import gui.component.MailBoxRenderer;
import gui.component.MailRenderer;
import gui.component.image.ResourceLoader;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Tom
 */
public class UIMain extends javax.swing.JFrame 
{

    public User user;
    public DefaultListModel modelContactGroup;
    public DefaultListModel modelMailBox;
    boolean mailmode;
    MailBox currentMailBox;
    ContactGroup currentContactGroup;
    
    MailRenderer mailRenderer;
    ContactRenderer contactRenderer;
    MailBoxRenderer mailBoxRenderer;
    ContactGroupRenderer contactGroupRenderer;
    UIReresher refresher;
    
    private boolean synchronizing;
    
    public UIMain(User user) 
    {        
        initComponents();
        this.user=user;                
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        spnMail.setResizeWeight(0.1d);
        
        mailRenderer = new MailRenderer(user);
        mailBoxRenderer = new MailBoxRenderer();
        contactRenderer = new ContactRenderer(user);
        contactGroupRenderer = new ContactGroupRenderer();        
        currentMailBox=null;
        currentContactGroup=null;
        
        //load mail box
        modelMailBox = new DefaultListModel();
        MailBox[] mailboxes = user.databaseWorker.getAllMailBox(false);
        for (MailBox mailboxe : mailboxes)
        {
            modelMailBox.addElement(mailboxe);
        }
        
        //load contact groups        
        user.databaseWorker.getAllContactGroup(true);
        //load model       
        
        initInterface();
        btEmailActionPerformed(null);                
    }
    
    private void initInterface()
    {    
        btNewEmail.setVisible(false);
        btNewContact.setVisible(false);
        btNewContactGroup.setVisible(false); 
        lbEmail.setText("Connecté(e) en tant que " + user.Email);
        
        pnLeft.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnRight.setLayout(new FlowLayout(FlowLayout.RIGHT));
        btEmail.setIcon(new ImageIcon(ResourceLoader.class.getResource("new.png")));
        btContact.setIcon(new ImageIcon(ResourceLoader.class.getResource("contact.png")));
        btConfig.setIcon(new ImageIcon(ResourceLoader.class.getResource("config.png"))); 
        btSync.setIcon(new ImageIcon(ResourceLoader.class.getResource("sync.png")));
        updateName();
        if (user.SyncPeriod==0)
        {
            chbSync.setSelected(false);
            cboxSync.setEnabled(false);
        }
        else
        {
            chbSync.setSelected(true);
            cboxSync.setEnabled(true);
            cboxSync.setSelectedItem(String.valueOf(user.SyncPeriod));
        }
        reloadContactGroupModel();
        updateUI();
        refresher = new UIReresher(this);
        new Thread(refresher).start();
    }
    
    public void updateName()
    {
        lbWelcome.setText("Bonjour, "+user.Username);
    }
    
    public void loadEmailMode()
    {
        btSync.setVisible(true);
        list.setCellRenderer(mailBoxRenderer);
        list.setModel(modelMailBox);       
        btNewEmail.setVisible(true);
        btNewContact.setVisible(false);
        btNewContactGroup.setVisible(false);
        mailmode=true;                
        list.setSelectedValue(currentMailBox, true);
        loadMailToList(currentMailBox);       
    }
    
    public void loadContactMode()
    {         
        btSync.setVisible(false);
        list.setCellRenderer(contactGroupRenderer);
        list.setModel(modelContactGroup);               
        btNewContact.setVisible(true);
        btNewContactGroup.setVisible(true);
        btNewEmail.setVisible(false);
        mailmode=false; //means contact mode
        list.setSelectedValue(currentContactGroup, true);
        loadContactToList(currentContactGroup);        
    }
    
    void loadMailToList(MailBox box)
    {
        if (box!=null)
        {
            Mail[] mails = user.databaseWorker.loadMailFromBox(box,true);                
            if (mails!=null)
            {                    
                table.setCellRenderer(mailRenderer);
                table.setModel(box.mailModel);                
            }
        }    
        else
        {
            table.setModel(new DefaultComboBoxModel());
            //table.repaint();
        }
    }
    
    private void loadContactToList(ContactGroup group)
    {        
        if (group!=null)
        {
            Contact[] contacts = user.databaseWorker.loadContactFromGroup(group,true);
            if (contacts!=null)
            {
                table.setCellRenderer(contactRenderer);
                table.setModel(group.contactModel);
            }
        }
        else
        {
            table.setModel(new DefaultListModel());
            //table.repaint();
        }
    }
    
    private void updateUI()
    {
        Date currentDate=new Date(System.currentTimeMillis());
        long difference = currentDate.getTime() - user.LastSync.getTime();
        long insec = (difference/1000) % 60;
        long inmin = (difference/(60*1000)) % 60;
        long inhour = (difference/(60*60*1000));
        
        if (!synchronizing)
        {
            lbSync.setText("Dernier mis-à-jour il y a " + (inhour>0? inhour + " heure(s) ":"") + (inmin>0? inmin+" minute(s) ":"") + insec + " second(s)");
        }
    }
    
    public void syncFail()
    {
        lbSync.setText("Synchronisation échouée. Vérifiez votre connexion.");
    }
    
    public void reloadContactGroupModel()
    {
        modelContactGroup= new DefaultListModel();
        for (ContactGroup ctg : user.contactgroup)
        {
            modelContactGroup.addElement(ctg);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        btConfig = new javax.swing.JButton();
        spnMail = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        pnLeft = new javax.swing.JPanel();
        btNewEmail = new javax.swing.JButton();
        btNewContact = new javax.swing.JButton();
        btNewContactGroup = new javax.swing.JButton();
        pnRight = new javax.swing.JPanel();
        btDeleteSelected = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        table = new javax.swing.JList();
        btEmail = new javax.swing.JToggleButton();
        btContact = new javax.swing.JToggleButton();
        lbWelcome = new javax.swing.JLabel();
        lbLogout = new javax.swing.JLabel();
        btSync = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        lbSync = new javax.swing.JLabel();
        cboxSync = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        chbSync = new javax.swing.JCheckBox();
        lbEmail = new javax.swing.JLabel();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Système d'email ThunderPig");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        btConfig.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConfigActionPerformed(evt);
            }
        });

        jScrollPane2.setMinimumSize(new java.awt.Dimension(150, 23));
        jScrollPane2.setPreferredSize(new java.awt.Dimension(250, 130));

        list.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
        list.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setMaximumSize(new java.awt.Dimension(250, 80));
        list.setMinimumSize(new java.awt.Dimension(250, 80));
        list.setPreferredSize(new java.awt.Dimension(250, 80));
        list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(list);

        spnMail.setLeftComponent(jScrollPane2);

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btNewEmail.setText("Créer email");
        btNewEmail.setPreferredSize(new java.awt.Dimension(87, 30));
        btNewEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNewEmailActionPerformed(evt);
            }
        });

        btNewContact.setText("Créer contact");
        btNewContact.setPreferredSize(new java.awt.Dimension(99, 30));
        btNewContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNewContactActionPerformed(evt);
            }
        });

        btNewContactGroup.setText("Manager les groupes de contact");
        btNewContactGroup.setPreferredSize(new java.awt.Dimension(151, 30));
        btNewContactGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNewContactGroupActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnLeftLayout = new javax.swing.GroupLayout(pnLeft);
        pnLeft.setLayout(pnLeftLayout);
        pnLeftLayout.setHorizontalGroup(
            pnLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnLeftLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btNewEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btNewContact, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btNewContactGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnLeftLayout.setVerticalGroup(
            pnLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnLeftLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btNewContact, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btNewEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btNewContactGroup, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btDeleteSelected.setText("Supprimer les sélections");
        btDeleteSelected.setPreferredSize(new java.awt.Dimension(147, 30));
        btDeleteSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteSelectedActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnRightLayout = new javax.swing.GroupLayout(pnRight);
        pnRight.setLayout(pnRightLayout);
        pnRightLayout.setHorizontalGroup(
            pnRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnRightLayout.createSequentialGroup()
                .addGap(167, 167, 167)
                .addComponent(btDeleteSelected, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnRightLayout.setVerticalGroup(
            pnRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnRightLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btDeleteSelected, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(pnLeft, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnRight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(pnLeft, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(pnRight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(table);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                .addContainerGap())
        );

        spnMail.setRightComponent(jPanel1);

        btEmail.setText("Email");
        btEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEmailActionPerformed(evt);
            }
        });

        btContact.setText("Contact");
        btContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btContactActionPerformed(evt);
            }
        });

        lbWelcome.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        lbLogout.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbLogout.setForeground(java.awt.Color.blue);
        lbLogout.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbLogout.setText("(déconnexion)");
        lbLogout.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lbLogout.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbLogoutMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                lbLogoutMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                lbLogoutMouseExited(evt);
            }
        });

        btSync.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSyncActionPerformed(evt);
            }
        });

        cboxSync.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "10", "15", "30", "60" }));
        cboxSync.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboxSyncActionPerformed(evt);
            }
        });

        jLabel1.setText("minutes");

        chbSync.setText("Mettre à jour chaque");
        chbSync.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chbSyncActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(lbSync, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(chbSync)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cboxSync, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbSync, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(cboxSync, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(chbSync))
        );

        lbEmail.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbEmail.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbEmail.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        lbEmail.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbEmailMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                lbEmailMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                lbEmailMouseExited(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btContact, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btSync, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btConfig, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbWelcome, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lbEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbLogout))
                    .addComponent(spnMail, javax.swing.GroupLayout.DEFAULT_SIZE, 1042, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbWelcome, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lbLogout, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lbEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btContact, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btConfig, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSync, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(spnMail)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEmailActionPerformed
        btContact.setSelected(false);            
        btEmail.setSelected(true);
        loadEmailMode();
    }//GEN-LAST:event_btEmailActionPerformed

    private void btContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btContactActionPerformed
        btEmail.setSelected(false);            
        btContact.setSelected(true);
        loadContactMode();
    }//GEN-LAST:event_btContactActionPerformed

    private void btConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfigActionPerformed
        UIConfig config = new UIConfig(this);
        config.setVisible(true);
    }//GEN-LAST:event_btConfigActionPerformed

    private void lbLogoutMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseEntered
        lbLogout.setForeground(Color.RED);
    }//GEN-LAST:event_lbLogoutMouseEntered

    private void lbLogoutMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseExited
        lbLogout.setForeground(Color.BLUE);
    }//GEN-LAST:event_lbLogoutMouseExited

    private void lbLogoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseClicked
        this.setVisible(false);
        UILogin log = new UILogin();
        log.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_lbLogoutMouseClicked

    private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked
        if (mailmode)
        {
            MailBox mailbox = (MailBox)list.getSelectedValue();            
            loadMailToList(mailbox);
            currentMailBox=mailbox; 
        }
        else
        {
            ContactGroup contactgroup = (ContactGroup)list.getSelectedValue();
            loadContactToList(contactgroup);
            currentContactGroup=contactgroup;
        }        
    }//GEN-LAST:event_listMouseClicked

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        //check if double click
        if (evt.getClickCount()==2)
        {   
            //check mode
            if (mailmode)
            {
                //afficher le message
                Mail m = (Mail)table.getSelectedValue();
                if (m!=null)
                {
                    user.databaseWorker.setMailRead(m);                    
                    UIViewMail vm = new UIViewMail(this, m);
                    vm.setVisible(true);
                }
            }
            else
            {
                //afficher le contact
                Contact ct = (Contact)table.getSelectedValue();
                if (ct!=null)
                {
                    UIContact vc = new UIContact(this, ct, UIContact.ContactViewMode.VIEW);
                    vc.setVisible(true);
                }
            }
        }  
    }//GEN-LAST:event_tableMouseClicked

    private void btNewEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNewEmailActionPerformed
        UINewMail nm = new UINewMail(this);
        nm.setVisible(true);
    }//GEN-LAST:event_btNewEmailActionPerformed

    private void btNewContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNewContactActionPerformed
        UIContact vc = new UIContact(this,null,UIContact.ContactViewMode.NEW);
        vc.setVisible(true);
    }//GEN-LAST:event_btNewContactActionPerformed

    private void btNewContactGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNewContactGroupActionPerformed
        //load all contact to all group
        for (ContactGroup ctg : user.contactgroup)
        {
            user.databaseWorker.loadContactFromGroup(ctg, true);
        }
        UIContactGroup contactGroup = new UIContactGroup(this);
        contactGroup.setVisible(true);
    }//GEN-LAST:event_btNewContactGroupActionPerformed

    private void btDeleteSelectedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteSelectedActionPerformed
        List selecteds = table.getSelectedValuesList();
        if (selecteds.isEmpty())
        {
            JOptionPane.showMessageDialog(this, "Aucune de sélection!", "", JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            int result=JOptionPane.showConfirmDialog(this, "Vous êtes sur(e) pour la suppression?", "Confimation de suppression", JOptionPane.YES_NO_OPTION);
            if (result==JOptionPane.YES_OPTION)
            {
                selecteds.stream().forEach((item) -> 
                { 
                    if (mailmode)
                    {
                        Mail m = (Mail)item;
                        //remove from database
                        user.databaseWorker.deleteMail(m.MailID);
                        //remove from list
                        currentMailBox.mailModel.removeElement(m);
                    }
                    else
                    {
                        Contact c = (Contact)item;
                        //remove from database
                        user.databaseWorker.deleteContact(c.ContactID);
                        //remove from list
                        currentContactGroup.contactModel.removeElement(c);
                    }
                });
                
                JOptionPane.showMessageDialog(this, selecteds.size()+" sélections ont été supprimées", "", JOptionPane.INFORMATION_MESSAGE);
            }            
        }        
    }//GEN-LAST:event_btDeleteSelectedActionPerformed

    private void btSyncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSyncActionPerformed
        //do the synchronization                
        Thread syncThread = new Thread(new Synchroniser(this));
        syncThread.start();
    }//GEN-LAST:event_btSyncActionPerformed

    private void chbSyncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbSyncActionPerformed
        if (chbSync.isSelected())
        {
            cboxSync.setEnabled(true);
            user.SyncPeriod=Integer.parseInt(cboxSync.getSelectedItem().toString());            
        }
        else
        {
            cboxSync.setEnabled(false);
            user.SyncPeriod=0;
        }
        //update database
        user.databaseWorker.updateUserProperty("SyncPeriod", user.SyncPeriod);
    }//GEN-LAST:event_chbSyncActionPerformed

    private void cboxSyncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboxSyncActionPerformed
        if (user!=null && cboxSync.getSelectedItem()!=null)
        {
            user.SyncPeriod=Integer.parseInt(cboxSync.getSelectedItem().toString());            
            //update database
            user.databaseWorker.updateUserProperty("SyncPeriod", user.SyncPeriod);
        }
    }//GEN-LAST:event_cboxSyncActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        refresher.stopWorking();
    }//GEN-LAST:event_formWindowClosed

    private void lbEmailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbEmailMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_lbEmailMouseClicked

    private void lbEmailMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbEmailMouseEntered
        // TODO add your handling code here:
    }//GEN-LAST:event_lbEmailMouseEntered

    private void lbEmailMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbEmailMouseExited
        // TODO add your handling code here:
    }//GEN-LAST:event_lbEmailMouseExited

    
    final class UIReresher implements Runnable
    {
        UIMain main;
        int tick;
        boolean working;
        
        public UIReresher(UIMain main)
        {
            this.main=main;
            tick=0;
            working=true;
        }
        @Override
        public void run() 
        {     
            while (working)
            {
                main.updateUI();
                if (tick==main.user.SyncPeriod)
                {
                    //call sync
                    main.btSyncActionPerformed(null);
                }
                try 
                {
                    tick++;       
                    Thread.sleep(60000);
                }
                catch (InterruptedException ex) 
                {
                    Logger.getLogger(UIMain.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }    
        
        public void stopWorking()
        {
            working=false;
        }
    }
    
    final class Synchroniser implements Runnable
    {
        UIMain main;
        public Synchroniser(UIMain main)
        {
            this.main=main;
        }
        
        @Override
        public void run() 
        {
            if (!synchronizing)
            {
                synchronizing=true;
                btSync.setEnabled(false);
                main.synchronizing=true;
                main.lbSync.setText("En synchronisation...");
                boolean result = main.user.databaseWorker.syncMail();   
                if (result)
                {
                    main.user.databaseWorker.updateLastSync();
                    main.lbSync.setText("Synchronisation completée");
                }
                else
                {
                    main.syncFail();
                }
                main.synchronizing=false;
                btSync.setEnabled(true);                
                loadMailToList(currentMailBox);
                synchronizing=false;                
            }
        }
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btConfig;
    private javax.swing.JToggleButton btContact;
    private javax.swing.JButton btDeleteSelected;
    private javax.swing.JToggleButton btEmail;
    private javax.swing.JButton btNewContact;
    private javax.swing.JButton btNewContactGroup;
    private javax.swing.JButton btNewEmail;
    private javax.swing.JButton btSync;
    private javax.swing.JComboBox cboxSync;
    private javax.swing.JCheckBox chbSync;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lbEmail;
    private javax.swing.JLabel lbLogout;
    private javax.swing.JLabel lbSync;
    private javax.swing.JLabel lbWelcome;
    private javax.swing.JList list;
    private javax.swing.JPanel pnLeft;
    private javax.swing.JPanel pnRight;
    private javax.swing.JSplitPane spnMail;
    private javax.swing.JList table;
    // End of variables declaration//GEN-END:variables


}
